package com.zywl.service.impl;

import com.zywl.core.beans.Role;
import com.zywl.core.beans.RoleResRel;
import com.zywl.core.dao.mapper.sys.RoleMapper;
import com.zywl.core.dao.mapper.sys.RoleResRelMapper;
import com.zywl.service.RoleService;
import com.zywl.service.impl.base.BaseServiceImpl;
import com.zywl.utils.utils.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleResRelMapper relMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(Role t, String ids) throws Exception {
        mapper.insert(t);
        if (StringUtils.isNotEmpty(ids)) {
            String[] id_s = ids.split(Constants.STRING_SPLIT);
            RoleResRel rel = null;
            for (String id : id_s) {
                rel = new RoleResRel();
                rel.setRrsRoleId(t.getRoeId());
                rel.setRrsResId(Long.parseLong(id));

                relMapper.insert(rel);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Role t, String ids) throws Exception {
        mapper.updateByPrimaryKey(t);
        relMapper.deleteByRoleId(t.getRoeId());
        if (StringUtils.isNotEmpty(ids)) {
            String[] id_s = ids.split(Constants.STRING_SPLIT);
            RoleResRel rel = null;
            for (String id : id_s) {
                rel = new RoleResRel();
                rel.setRrsRoleId(t.getRoeId());
                rel.setRrsResId(Long.parseLong(id));

                relMapper.insert(rel);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(Long id) throws Exception {
        mapper.deleteByPrimaryKey(id);
        relMapper.deleteByRoleId(id);
    }

    @Override
    public Role getById(Long id) throws Exception {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> getLevelDownRolesByRoleId(String roleId) throws Exception {
//        return mapper.getLevelDownRolesByRoleId(roleId);
        return null;
    }

    @Override
    public int getMaxLevel() throws Exception {
//        return mapper.getMaxLevel();
        return 0;
    }

    @Override
    public boolean roleNameExist(String roleName) throws Exception {
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("roe_name", roleName);
        List<Role> roles = mapper.getListByParams(condition);
        if (roles != null && !roles.isEmpty()) {
            return true;
        }
        return false;
    }
}
